#import "SEGMultipartfileuploadManager.h"

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif


#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

static id _multipartFileUploadManager;
static dispatch_once_t onceToken;

@interface SEGMultipartfileuploadManager()
@property (nonatomic, copy) NSString *urlString;
@end

@implementation SEGMultipartfileuploadManager
#pragma mark - SINGLE----BEGIN----
+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _multipartFileUploadManager = [[self alloc] init];
    });
    return _multipartFileUploadManager;
}

+(void)destroyResource{
    onceToken = 0;
    _multipartFileUploadManager = nil;
}

#pragma mark - SINGLE----END----

#pragma mark - HTTP----BEGIN----

/**
 图片上传-多图-添加服务器区分
 
 @author Sam
 @param data 图片二进制数组
 @param serviceType 0：b端服务，1：c端服务
 @param progress 上传进度
 @param completed 上传完成回调
 */
-(void)requestMultipartfileuploadWithData:(NSArray<NSData*>*)data serviceType:(NSString*)serviceType progress:(void(^)(double progressValue))progress completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{
     
     NSString *urlString = self.urlString;
     if ([serviceType isEqualToString:@"0"]) urlString = [self.urlString stringByReplacingOccurrencesOfString:kClientRootURL withString:kBrowerRootURL];
     
     [SEGHTTPBusinessManager seg_uploadImagesWithURLString:urlString parameters:nil sources:data progress:progress completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
         if (!isSuccessed || result == nil) {
             completed(NO,nil,codeType,error.localizedDescription);
             return;
         }
         
         if (![result isKindOfClass:[NSDictionary class]]) {
             completed(NO,nil,codeType,error.localizedDescription);
             return;
         }
         
         self.multipartFileUpload = [SEGMultipartfileuploadModel yy_modelWithDictionary:result];
         completed(YES,result,codeType,error.localizedDescription);
         return;
     }];
 }


/// H5多图上传接口
/// @param data 图片二进制数组
/// @param serviceType 0：b端服务，1：c端服务
/// @param progress 上传进度
/// @param completed 上传完成回调
-(void)requestH5MultipartfileuploadWithData:(NSArray<NSData*>*)data serviceType:(NSString*)serviceType progress:(void(^)(double progressValue))progress completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed {
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-app/common/multiUpload.json",nil];
    if ([serviceType isEqualToString:@"0"]) urlString = [self.urlString stringByReplacingOccurrencesOfString:kClientRootURL withString:kBrowerRootURL];
    
    [SEGHTTPBusinessManager seg_uploadImagesWithURLString:urlString parameters:nil sources:data progress:progress completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed || result == nil) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        if (![result isKindOfClass:[NSDictionary class]]) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        self.multipartFileUpload = [SEGMultipartfileuploadModel yy_modelWithDictionary:result];
        completed(YES,result,codeType,error.localizedDescription);
        return;
    }];
}

-(void)requestMultipartfileuploadWithData:(NSArray<NSData*>*)data progress:(void(^)(double progressValue))progress completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{
    
    [SEGHTTPBusinessManager seg_uploadImagesWithURLString:self.urlString parameters:nil sources:data progress:progress completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed || result == nil) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        if (![result isKindOfClass:[NSDictionary class]]) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        self.multipartFileUpload = [SEGMultipartfileuploadModel yy_modelWithDictionary:result];
        completed(YES,result,codeType,error.localizedDescription);
        return;
    }];
}

/**
 图片上传-多图

 @param imagePaths 图片的本地路径数组
 @param progress 进度
 @param completed 回调
 */
- (void)requestMultipartfileuploadWithImagePaths:(NSArray<NSString *>*)imagePaths progress:(void(^)(double progressValue))progress completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed {
    NSMutableArray<NSData *> *imageDatas = [[NSMutableArray alloc] init];
    for (NSString * path in imagePaths) {
        //拼接图片沙盒路径
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSArray *pathArray = [path componentsSeparatedByString:@"/"];
        NSString *picName = pathArray[pathArray.count -1];
        NSString *pathStr = [NSString stringWithFormat:@"%@/%@", documentPath, picName];
        
        NSData* data = [NSData dataWithContentsOfFile:pathStr];
        if (data) {
            [imageDatas addObject:data];
        }
    }
    
    [self requestMultipartfileuploadWithData:imageDatas progress:progress completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        completed(isSuccessed, result, codeType, errorMessage);
    }];
}

/**
 图片上传-多图
 
 @author Sam
 @param img 图片二进制数组
 @param progress 上传进度
 @param completed 上传完成回调
 */
-(void)requestMultipartfileuploadWithImage:(NSArray<UIImage*>*)img progress:(void(^)(double progressValue))progress completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{
    
    NSMutableArray *dataArray = [NSMutableArray array];
    [img enumerateObjectsUsingBlock:^(id subItem, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImage *image = nil;
        if ([subItem isKindOfClass:[NSData class]]) {
            image = [UIImage imageWithData:subItem];
        }
        if ([subItem isKindOfClass:[UIImage class]]) {
            image = subItem;
        }
        //调正图片方向
        image = [SEGUtils fixOrientation:image];
        
        //压缩图片
        CGFloat hh = MAX(image.size.width, image.size.height);
        UIImage *scaleImageView = nil;
        if (hh>1280)
        {
            CGFloat wh = 1280/hh;
            scaleImageView = [SEGUtils OriginImage:image scaleToSize:CGSizeMake(image.size.width*wh, image.size.height*wh)];
        }
        else
        {
            scaleImageView = [SEGUtils OriginImage:image scaleToSize:CGSizeMake(image.size.width, image.size.height)];
        }
        
        NSData *data = UIImageJPEGRepresentation(scaleImageView, 0.8);//获取图片数据
        if (data) {
            [dataArray addObject:data];
        }
    }];
    
    [self requestMultipartfileuploadWithData:dataArray progress:progress completed:completed];
}

-(void)requestMultipartfileuploadWithDetailData:(NSArray<SEGUploadFileModel*>*)detailData progress:(void(^)(double progressValue))progress completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{
    [SEGHTTPBusinessManager seg_uploadDatasWithURLString:self.urlString parameters:nil detailSources:detailData progress:progress completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed || result == nil) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        if (![result isKindOfClass:[NSDictionary class]]) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        self.multipartFileUpload = [SEGMultipartfileuploadModel yy_modelWithDictionary:result];
        completed(YES,result,codeType,error.localizedDescription);
        return;
    }];
}

#pragma mark - HTTP----END----

#pragma mark - GETTER----BEGIN----
-(SEGMultipartfileuploadModel *)multipartFileUpload{
    if (!_multipartFileUpload) {
        _multipartFileUpload = [[SEGMultipartfileuploadModel alloc]init];
    }
    return _multipartFileUpload;
}

-(NSString *)urlString{
    if (!_urlString) {
        _urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-app/common/multipartFileUpload.json",nil];
    }
    return _urlString;
}
#pragma mark - GETTER----END----
@end
